<?php
class AppRecord{
	public $ID;
	public $Name=array();
	function __construct($id, $name){
		$this->ID = $id;
		$this->Name = unpack('C*', $name ) ;
	}
	function getName(){
		return implode(array_map("chr",  $this->Name )) ;
	}
}
class DataAppManager{
	private $Apps = array();
	function __construct(){
	}
	static function swap($bytebuffer){
		$obj = new DataAppManager();
		$num_of_apps = DataUtil::readInt32( $bytebuffer ) ;
		for($i = 0; $i < $num_of_apps; $i++){
			$obj->Apps[] = new AppRecord(DataUtil::readInt32( $bytebuffer ) ,implode(array_map("chr",  DataUtil::readBBin( $bytebuffer )  )) );
		}
		return $obj;
	}
	function getAppsID(){
		$rs = array();
		if(is_array($this->Apps)){
			foreach($this->Apps as $app){
				$rs[] = $app->ID;
			}
		}
		return $rs;
	}
	function getAppName($appid){
		if(is_array($this->Apps)){
			foreach($this->Apps as $app){
				if($app->ID == $appid){
					return $app->getName();
				}
			}
		}
	}
	function addApp($id, $name){
		$this->Apps[] = new AppRecord($id, $name);
	}
	function getBinSize(){
		$size = 0;
		$size += 4 ;
		if(is_array($this->Apps)){
			foreach($this->Apps as $app){
				$size += 4 ;
				$size += 1  + count($app->Name);
			}
		}
		return $size;
	}
	function getBinary(){
		$buf = ByteBuffer::allocate( $this->getBinSize() ) ;
		DataUtil::writeInt32( $buf , count($this->Apps) ) ;
		if(is_array($this->Apps)){
			foreach($this->Apps as $app){
				DataUtil::writeInt32( $buf , $app->ID ) ;
				DataUtil::writeBBin( $buf , $app->Name ) ;
			}
		}
		return  $buf ->_array() ;
	}
}
?>